package com.banmao.mpDynamicDS.config;

import com.banmao.dynamicDS.config.DynamicDataSource;
import com.banmao.dynamicDS.datasource.DatasourceContextHolder;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
// 加 MapperScan 才能注入 或者在 DataSource 的 Bean 定义上加 @Primary
//@MapperScan(basePackages = "com.banmao")
public class DatasourceConfig {

    @Value("${spring.datasource.default:DEFAULT}")
    private String defalutDatasource;

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource ds1() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource ds2() {
        return DataSourceBuilder.create().build();
    }

    @Bean("dynamicDataSource")
    public DynamicDataSource dynamicDataSource(Map<String, DataSource> dataSourceMap) {
        HashMap<Object, Object> targetDatasources = new HashMap<>(dataSourceMap);

        defalutDatasource = "DEFAULT".equals(defalutDatasource) ? dataSourceMap.keySet().stream().findFirst().get() : defalutDatasource;

        DatasourceContextHolder.setDefaultdatasource(defalutDatasource);

        return new DynamicDataSource(targetDatasources, dataSourceMap.get(defalutDatasource));
    }

    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource) {
        return new JdbcTemplate(dynamicDataSource);
    }

    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource) {
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(dynamicDataSource);
        return mybatisSqlSessionFactoryBean;
    }


}
